package org.nvframe.component.stats;

import org.nvframe.component.AbstractComponent;
import org.nvframe.component.property.PropertyManager;
import org.nvframe.entity.Entity;
import org.nvframe.event.EventService;
import org.nvframe.event.eventtype.DamageEvent;
import org.nvframe.event.eventtype.DamageListener;
import org.nvframe.event.eventtype.DeathEvent;
import org.nvframe.event.eventtype.StatsEvent;
import org.nvframe.event.eventtype.StatsListener;
import org.nvframe.exception.NVFrameException;
import org.nvframe.manager.ConfigManager;
import org.nvframe.util.Settings;

/**
 * 
 * @author Nik Van Looy
 */
public class Health extends AbstractComponent implements StatsListener, DamageListener {
	
	private PropertyManager propManager;

	public Health(String id, Entity owner, Settings settings) throws NVFrameException {
		super(id, owner);

		propManager = (PropertyManager) owner.getComponent(PropertyManager.class);
		
		if(propManager == null)
			throw new NVFrameException("cannot load health component without " +
					"a propertymanager present [entityid: " + owner.getId() + "]");
		
		// add the health property to the PropertyManager component
		propManager.setProperty("health", settings.getInt("health", 100));
		
		EventService.getInstance().addEventListener(this);
	}

	@Override
	public void statsChanged(StatsEvent event) {
		if(propManager.getValueInt("health") <= 0) {		
			// notify owner that he is dead
			EventService.getInstance().fireEvent(new DeathEvent(owner));
			
			// set all ocmponents on "inactive"
			owner.removed();
		}
	}

	@Override
	public void damageReceived(DamageEvent event) {
		if(event.getTarget() != owner)
			return; // no damage to this entity
		
		propManager.getPropertyInt("health").substract(event.getDamagePoints());

		if(ConfigManager.getInstance().getActive("debugMode"))
			System.out.println(event.getTarget().getId() + " received damage from " + event.getSource().getId() + 
					" | DP: " + event.getDamagePoints() + " | HP: " + propManager.getValueInt("health"));
		
		// notify the owner thath the stats changed
		EventService.getInstance().fireEvent(new StatsEvent("health"), owner);
	}
	
	@Override
	public void removed(Entity entity) {
		EventService.getInstance().removeEventListener(this);
	}

}
